package com.yhgarden.bbs.service.impl.system;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yhgarden.bbs.entity.system.Menu;
import com.yhgarden.bbs.entity.system.Role;
import com.yhgarden.bbs.entity.system.SystemUser;
import com.yhgarden.bbs.entity.system.UserRole;
import com.yhgarden.bbs.entity.vo.role.UserIdRoleIdsVo;
import com.yhgarden.bbs.entity.vo.role.UserRoleNameVo;
import com.yhgarden.bbs.entity.vo.systemUser.SystemUserRolesVo;
import com.yhgarden.bbs.mapper.system.RoleMapper;
import com.yhgarden.bbs.mapper.system.UserRoleMapper;
import com.yhgarden.bbs.model.constants.YhbbsConstants;
import com.yhgarden.bbs.model.enums.StatusCode;
import com.yhgarden.bbs.model.helper.Pager;
import com.yhgarden.bbs.model.helper.SortPointer;
import com.yhgarden.bbs.model.response.BaseResponse;
import com.yhgarden.bbs.service.api.system.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private ExecutorService executorService;

    @Override
    public BaseResponse createOrUpdate(HttpSession session, Role role) throws Exception {
        SystemUserRolesVo systemUserRolesVo = (SystemUserRolesVo) session.getAttribute(YhbbsConstants.SYSTEM_USER_SESSION_KEY);
        SystemUser sessionUser = systemUserRolesVo.getSystemUser();
        String userId = sessionUser.getId();
        BaseResponse response = new BaseResponse(StatusCode.SUCCESS);
        if(role.getId() == null){
            String uuid = UUID.randomUUID().toString();
            role.setId(uuid);
            role.setCreatedBy(userId);
            roleMapper.create(role);
        }else {
            role.setUpdatedBy(userId);
            roleMapper.update(role);
        }
        executorService.submit(()->{
            String pid = role.getPid();
            if(pid != null){
                Role pRole = new Role();
                pRole.setId(pid);
                pRole.setHasChildren(true);
                roleMapper.update(pRole);
            }
        });
        response.setData(role);
        return response;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse handleUserRole(UserIdRoleIdsVo userIdRoleIdsVo) throws Exception {
        BaseResponse response = new BaseResponse(StatusCode.SUCCESS);
        String userId = userIdRoleIdsVo.getUserId();
        //先删除后写入
        UserRole userRole = new UserRole();
        userRole.setUserId(userId);
        userRoleMapper.deleteByExample(userRole);
        //批量写入
        List<UserRole> userRoleList = new ArrayList<>();
        List<String> roleIds = userIdRoleIdsVo.getRoleIds();
        roleIds.forEach(roleId->{
            UserRole userRoleTemp = new UserRole();
            String uuid = UUID.randomUUID().toString();
            userRoleTemp.setId(uuid);
            userRoleTemp.setUserId(userId);
            userRoleTemp.setRoleId(roleId);
            userRoleList.add(userRoleTemp);
        });
        userRoleMapper.batchCreate(userRoleList);
        return response;
    }

    @Override
    public BaseResponse getById(String id) {
        BaseResponse response = new BaseResponse(StatusCode.SUCCESS);
        Role role = roleMapper.getById(id);
        response.setData(role);
        return response;
    }

    @Override
    public BaseResponse getByPid(String pid) {
        BaseResponse response = new BaseResponse(StatusCode.SUCCESS);
        List<Role> roles = roleMapper.getByPid(pid);
        executorService.submit(()->{
            if(roles.size() == 0){
                Role pRole = new Role();
                pRole.setId(pid);
                pRole.setHasChildren(false);
                roleMapper.update(pRole);
            }
        });
        response.setData(roles);
        return response;
    }

    @Override
    public BaseResponse getByUserId(String userId) {
        BaseResponse response = new BaseResponse(StatusCode.SUCCESS);
        List<UserRoleNameVo> userRoleList = userRoleMapper.getByUserId(userId);
        response.setData(userRoleList);
        return response;
    }


    @Override
    public BaseResponse getByIdMoreDetail(String id) {
        BaseResponse response = new BaseResponse(StatusCode.SUCCESS);
        Role role = roleMapper.getByIdMoreDetail(id);
        response.setData(role);
        return response;
    }


    @Override
    public BaseResponse query(Role role) {
        BaseResponse response = new BaseResponse(StatusCode.SUCCESS);
        Pager pager = role.getPager();
        SortPointer sortPointer = role.getSortPointer();
        if(sortPointer == null){
            sortPointer = new SortPointer();
        }
        PageHelper.startPage(pager.getCurrentPage(),pager.getPageSize());
        List<Role> roleList = roleMapper.query(role,sortPointer.getOrder(),sortPointer.getField());
        PageInfo result = new PageInfo<Role>(roleList);
        response.setData(result);
        return response;
    }


    @Override
    public BaseResponse queryForList(Role role) {
        BaseResponse response = new BaseResponse(StatusCode.SUCCESS);
        Pager pager = role.getPager();
        SortPointer sortPointer = role.getSortPointer();
        if(sortPointer == null){
            sortPointer = new SortPointer();
        }
        PageHelper.startPage(pager.getCurrentPage(),pager.getPageSize());
        List<Role> roleList = roleMapper.queryForList(role,sortPointer.getOrder(),sortPointer.getField());
        PageInfo result = new PageInfo<Role>(roleList);
        response.setData(result);
        return response;
    }


    @Override
    public BaseResponse queryMoreDetail(Role role) {
        BaseResponse response = new BaseResponse(StatusCode.SUCCESS);
        Pager pager = role.getPager();
        SortPointer sortPointer = role.getSortPointer();
        if(sortPointer == null){
            sortPointer = new SortPointer();
        }
        PageHelper.startPage(pager.getCurrentPage(),pager.getPageSize());
        List<Role> roleList = roleMapper.queryMoreDetail(role,sortPointer.getOrder(),sortPointer.getField());
        PageInfo result = new PageInfo<Role>(roleList);
        response.setData(result);
        return response;
    }


    @Override
    public BaseResponse delete(String id) {
        BaseResponse response = new BaseResponse(StatusCode.SUCCESS);
        roleMapper.delete(id);
        return response;
    }

}
